<?php
declare (strict_types = 1);

namespace app\command\Pixel;

use app\constant\CommonConstant;
use app\constant\ModelConstant;
use app\event\PushOrderToShopify;
use app\helpers\UtilHelper;
use app\model\BatchUpdate;
use app\model\FacebookPixels;
use app\model\LineItems;
use app\model\Notify;
use app\model\Orders;
use app\model\PixelLogs;
use app\model\ShopsPayment;
use app\queue\TestQueue;
use app\service\pixel\FaceBookPixelTrack;
use app\service\pixel\FacebookService;
use app\service\shopify\action\graph\OrderGraph;
use app\service\shopify\action\graph\ProductGraph;
use app\trait\OrderTrait;
use app\trait\PaymentTrait;
use app\trait\ShopifyTrait;
use Carbon\Carbon;
use Omnipay\Omnipay;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\facade\Cache;
use think\facade\Event;
use think\facade\Queue;
use think\helper\Arr;
use function Clue\StreamFilter\fun;

class FacebookPixelTrackCMD extends Command
{
    private int $limit = 100;
    protected function configure()
    {
        // 指令配置
        $this->setName('fb:track')
            //->addOption("date",'d', Option::VALUE_OPTIONAL, '指定日期')
            ->addOption("id",'id', Option::VALUE_OPTIONAL, '指定ID')
            ->addOption("shop_code",'shop_code', Option::VALUE_OPTIONAL, '指定店铺')
            ->setDescription('fb像素上报');
    }

    protected function execute(Input $input, Output $output)
    {
        $options = $input->getOptions();
        foreach (range(1,99999) as $page){
            dump("******************正在处理第".$page." 页数据********");
            $rows = $this->getPixelLogs($page,$options);
            if($rows->isEmpty()) break;
            $this->startTrack($rows);
        }
    }


    private function getPixelLogs($page,$options)
    {
        $offset = ($page - 1) * $this->limit;
        return PixelLogs::where('is_track',ModelConstant::STATUS_OFF)
                          ->where("platform", CommonConstant::TRAFFIC_SOURCE_FB)
                         ->where('created_at','<=',Carbon::now()->startOfDay()->toDateTimeString())
                          ->when($id = Arr::get($options,'id',0),function ($q) use ($id){
                              $q->where('id',$id);
                          })
                          ->when($shop_code = Arr::get($options,'shop_code'),function ($q) use ($shop_code){
                              $q->where('shop_code',$shop_code);
                          })
                          ->limit($offset,$this->limit)
                          ->select();
    }

    private function startTrack(array|\think\Collection $rows)
    {
        $service = new FacebookService();
        $rows->each(function (PixelLogs $log) use ($service) {
            if($log->event_type == CommonConstant::FB_EVENT_PREVIEW){
                $service->trackViewApi($log);
            }else{
                $service->trackPurchaseApi($log);
            }
        });
    }


}
